package com.security.springboot.service;

import com.security.springboot.dao.UserDao;
import com.security.springboot.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto userDto = userDao.getUserByUsername(username);
        if (userDto == null) {
            return null;
        }
        List<String> permission = userDao.getUserRoles(userDto.getId());
        String[] permissionArray = new String[permission.size()];
        permission.toArray(permissionArray);
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword())
                .roles(permissionArray).build();
        return userDetails;
    }
}
